﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Globalization;
using System.Configuration.Assemblies;
using System.ComponentModel;

namespace Kokomo.Mirror.CliMetadata.Tables
{
	public class AssemblyRefRow : IMetadataRow
	{
		public ushort MajorVersion { get; set; }
		public ushort MinorVersion { get; set; }
		public ushort BuildNumber { get; set; }
		public ushort RevisionNumber { get; set; }
		public AssemblyFlags Flags { get; set; }
		public BlobRef PublicKey { get; set; }
		public StringRef Name { get; set; }
		public StringRef Culture { get; set; }
		public BlobRef HashValue { get; set; }

		public AssemblyName ToAssemblyName(MetadataContainer container)
		{
			if (container == null) throw new ArgumentNullException("container");

			AssemblyName assemblyName = new AssemblyName()
			{
				Name = container.GetString(this.Name),
				Version = new System.Version(
					this.MajorVersion,
					this.MinorVersion,
					this.BuildNumber,
					this.RevisionNumber
					),
				HashAlgorithm = AssemblyHashAlgorithm.SHA1
			};

			string culture = container.GetString(this.Culture);
			byte[] publicKeyData = container.GetBlob(this.PublicKey);
			byte[] publicKeyTokenData = container.GetBlob(this.HashValue);

			if (culture != null)
				assemblyName.CultureInfo = CultureInfo.GetCultureInfo(culture);
			if (publicKeyData != null)
				assemblyName.SetPublicKeyToken(publicKeyData);
			else if (publicKeyTokenData != null)
				assemblyName.SetPublicKeyToken(publicKeyTokenData);

			return assemblyName;
		}

		public override string ToString(MetadataContainer container)
		{
			AssemblyName name = this.ToAssemblyName(container);
			return name.ToString();
		}
	}
}
